package database;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class DBConnector {

    // Variabler
    private String username, password, dbUrl, hostname, port, dbName;
    private Connection conn;
    private Statement stmt;
    private ResultSet result;

    private static DBConnector dbc;

    private DBConnector() {
        try {
            hostname = "localhost";
            port = "3306";
            dbName = "firstmile";
            username = "root";
            password = "3306";
            dbUrl = "jdbc:mysql://" + hostname + ":" + port + "/" + dbName;
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(dbUrl, username, password);
            stmt = conn.createStatement();
            result = null;
        } catch (SQLException ex) {
            Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public ResultSet doQuery(String query) {
        result = null;
        try {
            result = stmt.executeQuery(query);

        } catch (SQLException ex) {
            Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public void doUpdate(String query) {
        try {

            stmt.executeUpdate(query);

        } catch (SQLException e) {
        }
    }

    public void closeResult() {
        try {
            if (result != null) {
                result.close();
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "SQL fejl: " + e.getLocalizedMessage());
        }
    }

    public void closeStmt() {
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "SQL fejl: " + e.getLocalizedMessage());
        }
    }

    public void closeConn() {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "SQL fejl: " + e.getLocalizedMessage());
        }
    }

    public static DBConnector getDBC() {
        if (dbc == null) {
            dbc = new DBConnector();
        }
        return dbc;
    }
}
